<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\model\ProductionPlanDetail;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class CostSharing
 * @package app\home\controller
 * 成本分摊
 */
class CostSharing extends BaseController
{
    protected $table='cost_share';
    protected $title='成本分摊';
    private $sessionKey='pageCostSharing';

    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['status','>',-1];
            if (isset($param['status'])&&$param['status']){
                $where[]=['status','=',$param['status']];
            }
            if (isset($param['id'])&&$param['id']){
                $where[]=['id','=',$param['id']];
            }
            $where1=[];
            foreach (['bar_code','mdName','specs'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $where1[]=[$i,'like','%'.$param[$i].'%'];
                }
            }
            if ($where1){
                $c_id=Db::name('cost_share_data_detail')
                    ->where($where1)
                    ->where('status',1)
                    ->column('cost_share_id');
                $where[]=['id','in',$c_id];
            }
            if (isset($param['orderDate'])&&$param['orderDate']){
                $times=explode('~',$param['orderDate']);
                $where[]=['orderDate','between',$times];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->where($where)
                ->field("*")
                ->paginate($rows);

            return table_assign(0, '', $list);
        } else {
            return view();
        }

    }
    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $postData=$this->param;


            $material_id=$postData['material_id']??[];
            $in_receipt_detail_id=$postData['in_receipt_detail_id']??[];
            $num=$postData['num']??[];
            $ftmxid=$postData['ftmxid']??[];
            $ftName=$postData['ftName']??[];
            $ftNum=$postData['ftNum']??[];
            $craft_detail_id=$postData['craft_detail_id']??[];
            $id=$postData['id']??0;

            $sharTime=$param['sharTime'];
            if (!$sharTime){
                return to_assign(1,'参数缺失');
            }else{
                $sTime=explode('~',$sharTime);
                $s_star=$sTime[0]??date('Y-m-d');
                $s_end=$sTime[1]??date('Y-m-d');
            }
            $param=[
                'sharType'=>$postData['sharType'],
                'orderDate'=>$postData['orderDate'],
                'sharTime'=>$postData['sharTime'],
                'sharStart'=>$s_star,
                'countPrice'=>0,
                'sharEnd'=>$s_end,
                'status'=>$postData['status'],
                'id'=>$postData['id']??0,
            ];
            if (!$ftName||!$ftNum||!$num){
                return to_assign(1,'参数缺失');
            }
            if ($postData['sharType']==1){
                if (!$material_id){
                    return to_assign(1,'参数缺失');
                }
            }else{
                if (!$craft_detail_id){
                    return to_assign(1,'参数缺失');
                }
            }
            Db::startTrans();
            $param['update_time']=time();
            $id=$param['id']??0;
            $countPrice=0;
            $countNum=0;
            foreach ($num as $n){
                $countNum+=$n;
            }
            try {
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $postData,$this->title);
                } else {
                    $param['create_time'] = time();
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $postData,$this->title);
                }
                Db::name('cost_share_data_detail')->where('cost_share_id',$id)
                    ->where('status','>',-1)
                    ->update(['status'=>-1,'deleted'=>time(),'update_time'=>time()]);
                foreach ($ftNum as $f=>$x){
                    if (!isset($ftName[$f])||!$ftName[$f]){
                        throw new Exception('参数缺失');
                    }
                    $countPrice+=$ftNum[$f];
                    $csdData=[
                        'cost_share_id'=>$id,
                        'name'=>$ftName[$f],
                        'price'=>$ftNum[$f],
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if (isset($ftmxid[$f])&&$ftmxid[$f]){
                        $csdData['id']=$ftmxid[$f];
                    }
                    Db::name('cost_share_detail')->save($csdData);
                }

                foreach ($num as $k=>$v){

                    $ftje=$countPrice*($num[$k]/$countNum);
                    $mxData=[
                        'cost_share_id'=>$id,
                        'material_dossier_id'=>$material_id[$k]??0,
                        'num'=>$num[$k],
                        'gxPrice'=>0,
                        'in_receipt_detail_id'=>$in_receipt_detail_id[$k]??0,
                        'craft_detail_id'=>$craft_detail_id[$k]??0,
                        'costPrice'=>$ftje,
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    if ($postData['sharType']==2){
                        $mxData['gxPrice']=$ftje/$num[$k];
                    }
                    if (isset($mxid[$k])&&$mxid[$k]){
                        $mxData['id']=$mxid[$k];
                    }
                    Db::name('cost_share_data_detail')->save($mxData);
                }

                Db::name($this->table)->where('id',$id)->update(['countPrice'=>$countPrice]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select username from fy_admin a where a.id=makeUser)username")->find();
                View::assign('detail', $detail);
                $csdList=Db::name('cost_share_detail')
                    ->where('status','>',-1)
                    ->where('cost_share_id',$id)->select();

                $csddList=Db::name('cost_share_data_detail')->alias('csdd')
                    ->leftJoin('material_dossier md ','md.id=csdd.material_dossier_id')
                    ->where('csdd.status','>',-1)
                    ->where('csdd.cost_share_id',$id)
                    ->field("csdd.*,md.name as mdName,md.bar_code,md.unit,md.specs,md.unit,
                    (select name from fy_craft c where c.id=(select caraf_id from fy_craft_route_detail crd where crd.id=csdd.craft_detail_id)) craft_name")
                    ->select();
                View::assign('csdList', $csdList);
                View::assign('csddList', $csddList);
            }
            View::assign('id', $id);
            View::assign('defalutTime', date('Y-m-d'));

            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $where[]=['status','=',2];
            $where[]=['yw_type','=','生产入库'];
            foreach (['bar_code','mdName','specs'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $limit=$this->param['limit']??10;
            $list=Db::name('ruku_view')
                ->where($where)
                ->field("*")
                ->where($where)->paginate($limit);
            View::assign('list',$list);
            return table_assign(0, '', $list);
        } else {
            return \view('mx');
        }

    }
    public function removeMx()
    {
        $id=$this->param['id'];
        try {
            Db::name('cost_share_data_detail')->where('id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            add_log('add', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'删除失败:'.$e->getMessage());
        }
        return to_assign();
    }
    public function removeFtMx()
    {
        $id=$this->param['id'];
        try {
            Db::name('cost_share_detail')->where('id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            add_log('add', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'删除失败:'.$e->getMessage());
        }
        return to_assign();
    }
//    public function confirm()
//    {
//        $id=$this->param['id']??0;
//        if (!$id){
//            return to_assign(1,'参数缺失');
//        }
//        $mx=Db::name('cost_share_data_detail')->where('status',1)->where('cost_share_id',$id)->count();
//        $ftmx=Db::name('cost_share_detail')->where('status',1)->where('cost_share_id',$id)->count();
//        if (!$mx||!$ftmx){
//            return to_assign(1,'请添加明细');
//        }
//        try {
//            Db::name($this->table)->where('id',$id)->update(['confirmUser'=>$this->uid,'status'=>2,'update_time'=>time(),'confirmTime'=>time()]);
//            add_log('apply', $id, $this->param,$this->title);
//        }catch (\Exception $e){
//            return to_assign(1,'操作失败:'.$e->getMessage());
//        }
//        return to_assign(0,'操作成功');
//    }
    /**
     * date:2024/4/18
     * 确认
     */
    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $mx=Db::name('cost_share_data_detail')->where('status',1)->where('cost_share_id',$id)->count();
        $ftmx=Db::name('cost_share_detail')->where('status',1)->where('cost_share_id',$id)->count();
        if (!$mx||!$ftmx){
            return to_assign(1,'请添加明细');
        }
        try {
            Db::name($this->table)->where('id',$id)->update([
                'makeUser'=>$this->uid,
                'status'=>2,
                'update_time'=>time(),'checkTime'=>time()]);
            Db::name('cost_share_detail')->where('status',1)->where('cost_share_id',$id)->update(['status'=>2,'update_time'=>time()]);
            Db::name('cost_share_data_detail')->where('status',1)->where('cost_share_id',$id)->update(['status'=>2,'update_time'=>time()]);
            add_log('check', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status=Db::name($this->table)->where('id','in',$id)->column('status');
            if (in_array('2',$status)){
                return  to_assign(1, "有已确认数据，不能删除");
            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('cost_share_data_detail')->where('cost_share_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('cost_share_detail')->where('cost_share_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }

    public function info()
    {
        $id=$this->param['id']??0;
        $detail = Db::name($this->table)->where('id', $id)->field("*,(select username from fy_admin a where a.id=makeUser)username")->find();
        View::assign('detail', $detail);
        $csdList=Db::name('cost_share_detail')
            ->where('status','>',-1)
            ->where('cost_share_id',$id)->select();

        $csddList=Db::name('cost_share_data_detail')->alias('csdd')
            ->leftJoin('material_dossier md ','md.id=csdd.material_dossier_id')
            ->where('csdd.status','>',-1)
            ->where('csdd.cost_share_id',$id)
            ->field("csdd.*,md.name as mdName,md.bar_code,md.unit,md.specs,md.unit,
                    (select name from fy_craft c where c.id=(select caraf_id from fy_craft_route_detail crd where crd.id=csdd.craft_detail_id)) craft_name")
            ->select();
        View::assign('csdList', $csdList);
        View::assign('csddList', $csddList);
        View::assign('id', $id);
        return view('info');
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $mStatus=['','草稿','已确认'];
        $list = Db::name($this->table)
            ->where($where)
            ->field("*")
            ->select()
            ->each(function ($item) use ($mStatus){
                $item['status']=$mStatus[$item['status']];
                return $item;
            });
        $title = [
            'id' => 'ID',
            'orderDate' => '单据日期',
            'countPrice' => '分摊费用合计(元)',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }
}